<?php
/* -----------------xhprof------------------------ */
/**/ 
if (@$_GET['xhprof'] == 1) {
    
    xhprof_enable();
// xhprof_enable(XHPROF_FLAGS_NO_BUILTINS); //不记录内置的函数
xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY); //同时分析CPU和Mem的开销
    $xhprof_on = true;
   
} else {
	header('Content-type: text/javascript');
}

/* -----------------xhprof------------------------ */


include_once "../include/fun.cache.php";
include_once "../include/fun.ip.php";


//$cache = new AdCache($redis_config,'cache');
/*	
$result_arr = array(
0=>array('adid'=>2,'stime'=>1364324400,'etime'=>1367866800,'status'=>1,'content'=>'content','orderid'=>'111','pushtype'=>'bbs','condition'=>array('city'=>'1,475','bbs'=>'439,109','car'=>'1_A_0,172,263','citycar'=>'1,475','time'=>array('stime'=>'2013-3-26 19:00:00,2013-3-26 20:00:00','etime'=>'2013-5-6 19:00:00,2013-5-10 20:00:00')) ),
1=>array('adid'=>2,'stime'=>1364324400,'etime'=>1367866800,'status'=>1,'content'=>'content','orderid'=>'111','pushtype'=>'car','condition'=>array('city'=>'2,507','bbs'=>'','car'=>'1_A_0,172,263','citycar'=>'1,475','time'=>array('stime'=>'2013-3-26 19:00:00','etime'=>'2013-5-6 19:00:00')) ),
3=>array('adid'=>2,'stime'=>1364324400,'etime'=>1367866800,'status'=>1,'content'=>'content','orderid'=>'111','pushtype'=>'nobbs','condition'=>array('city'=>'','bbs'=>'','car'=>'','citycar'=>'','time'=>array('stime'=>'','etime'=>'')) ),
);
print_r($result_arr);
*/
$pid = intval($_GET['pid']);
$cid = intval($_GET['cid']);	//condition  id 
$pushstyle = $_GET['style']?$_GET['style']:'js';	//pushstyle   html js  div  
$pushstyle = htmlspecialchars(trim($pushstyle));
if(!$pid ){
	exit;
}
$content = '';
$content_default =array(); 

if($pid ){
	if($result_arr = get_cache_ad($pid)){
	//if($result_arr){
		//echo '----------';
		print_r($result_arr); 
		
		//在开始和结束时间之间+状态status
		$result_arr = array_filter($result_arr, "playtime");//print_r($result_arr);
		
		 //在多段开始和结束时间之间
		$result_arr = array_filter($result_arr, "playtimes");//print_r($result_arr);
 
		//在 city  ip定位city
		$result_arr = array_filter($result_arr, "playcity");//print_r($result_arr);
		
		//在 条件定位
		if($cid ){
			
				
				$result_arr = array_filter($result_arr, "playbbs");//echo 'bbs'.'</br>' ;print_r($result_arr);
				$result_arr_tmp =$result_arr ;
				if(count($result_arr)>=2){
					$result_arr = array_filter($result_arr, "playlevel");//print_r($result_arr);
					if(!$result_arr){
						$result_arr =$result_arr_tmp ;
					}
				}
			
		}
	} //if cache end	

/////////////////////////////////-------------play ads -------------	

 
	if(count($result_arr)==1  && $result_arr ){	
		foreach($result_arr AS $ad_k=>$ad_v){
			
				$content = $ad_v['content'];
		}
		$pushid = $ad_v['id']; //广告位-投放id
		$orderid = $ad_v['orderid']; //广告位-投放定单id
	}elseif($result_arr){
	 
		if($rand_key=$_COOKIE['ad_more_'.$pid]){
			$rand_key=$rand_key-1;//echo '</br>'.$rand_key;
			foreach($result_arr AS $ad_k=>$ad_v){
				if(  $result_arr[$ad_k]['id'] !='default' && $result_arr[$ad_k]['id'] !='default_tmp' ){ 
				
					if($rand_key != $ad_k   ){
						$result_arr[$ad_k] = $ad_v;
					}else{
						unset($result_arr[$ad_k]);
					}
				}else{
						unset($result_arr[$ad_k]);
				}
			}
			
		}
		$rand_key=@array_rand($result_arr);//print_r($result_arr);
		$content=$result_arr[$rand_key]['content'];
		
		$pushid = $result_arr[$rand_key]['id']; //广告位-投放id
		$orderid = $result_arr[$rand_key]['orderid']; //广告位-投放定单id
		
		$out_time = time()+3600;
		setcookie('ad_more_'.$pid,$rand_key+1,$out_time,'/','xcar.com.cn');//+1是为数组id前移 去掉0从1开始
	}
}//if pid end


/******************log*******************************/
/***** ****/  
$adpid = $pid; //广告位id
//$pushid = $pushid; //广告位投放id
//$orderid;
if(!$ip){
	$ip = getip();
}
$timestamp = time();
if(!isset($_COOKIE['_Xdwuv'])){
	$tmpname = uniqid();
	
	$endtime3 = mktime(0,0,0,date('m')+6,date('d'),date('Y'));
	setcookie('_Xdwuv',$tmpname,$endtime3,'/','.xcar.com.cn');
	$uv = $tmpname;
}else{
	$uv = $_COOKIE['_Xdwuv'];
}



if($content){

	

	//$content = str_replace("'","\'",$content);
	$content = str_replace("\n","",$content);
	$content = str_replace("\r","",$content);
	$content = preg_replace(array("/<script/i","/<\/script/i"),array("<scr'+'ipt","</scr'+'ipt"),$content);
	/*
	$content .= $content."var _Ximgurl='http://dwp.xcar.com.cn/1.gif';
		if( document.location.protocol!='file:' ){
		 
			var _Xstr=_Ximgurl+'?'+'".$uv."'+'&'+'".$pushid."'+'&'+'".$adpid."'+'&'+'".$orderid."'+'&'+'".$ip."'+'&'+'".$timestamp."';
			var _Xpimgobj = new Image();
			_Xpimgobj.src = _Xstr;
		}
	";
	*/
 


	if($pushstyle == 'html'){
		$content = $content;
	}elseif($pushstyle == 'div'){	//div 定位 js 输出
		if($content){
			$content = "var ad_js_".$pid."='".$content."';\nif(document.getElementById('div_ad_js_".$pid."')!=null){document.getElementById('div_ad_js_".$pid."').innerHTML=ad_js_".$pid.";}\n";
		}else{
			$content = "if(document.getElementById('div_ad_js_".$pid."')!=null){document.getElementById('div_ad_js_".$pid."').style.display='none';}\n";
		}
	}else{	//直接输出 js  代码在哪里输出 广告代码就放在哪里
	
		$content = 'document.write(\''.$content.'\');';
	}
//echo $content;



echo $content;
}
//$msg1['message'] = $timestamp."-".$ip."-".$uv."-".$pushid."-".$adpid."-".$orderid."\n";
/******************log*******************************/
//------------function---------------

function playtime($result){
	
	$nowtime=time(); 
	//echo '</br>'.$result['stime'].'</br>'. $nowtime .'</br>'. $result['etime'];
	if ( $result['stime']<= $nowtime &&  $result['etime'] >=$nowtime  && $result['status'] == 1 ){
		//echo '</br>'.$result['stime'].'</br>'. $nowtime .'</br>'. $result['etime'];
		return true;
	}elseif ($result['id'] =='default' && $result['status'] == 0){
		return false;
	}elseif ( $result['id'] =='default_tmp'){
		return false;
	}elseif (    $result['etime'] <=$nowtime   && $result['status'] == 1 && $result['id'] !='default'  ){		//修改状态status
		del_cache_ad($result['adid'],$result['id']);
		return false;
	}

}
function playtimes($result){		//print_r($result);
	if ($result['condition']['time'] && $result['id'] !='default' ) {
		$nowtime=time();
		$stime_arr =	explode(",",$result['condition']['time']['stime']);//print_r($stime_arr);
		$etime_arr =	explode(",",$result['condition']['time']['etime']);//print_r($stime_arr);
		foreach($stime_arr AS $k=>$v){
			//echo '</br>'.$stime_arr[$k].'</br>'. $nowtime .'</br>'. $etime_arr[$k];
			//echo '</br>'.strtotime($stime_arr[$k]).'</br>'. $nowtime .'</br>'. strtotime($etime_arr[$k]);
			if ( $stime_arr[$k]<= $nowtime &&  $etime_arr[$k] >=$nowtime ){
				//echo '</br>'.$stime_arr[$k].'</br>'. $nowtime .'</br>'. $etime_arr[$k];
				return true;
			}
		}
	}
	
}

function playbbs($result){
	global $cid; 
	if ($result['condition']['bbs'] ) {
		$bbs_arr =	explode(",",$result['condition']['bbs']);//print_r($bbs_arr);
		//echo '</br>'.$cid.'</br>'. $result['condition']['bbs'];
		if (@in_array($cid, $bbs_arr)   ) {
			return true;
		}
	}else{
		return true;
	}
}


function playlevel($result){	//bbs car  的级别默认投放 优先级别低于直接投放的
	if ($result['condition']['default'] == 1  ) {
		return false;
	}else{
		return true;
	}
}

function playcity($result){
	global $city_id_name; 
	if ($result['condition']['city']) {
		$city_arr =	explode(",",$result['condition']['city']);//print_r($city_arr);
		//echo '</br>'.$cid.'</br>'. $result['condition']['city'];	
		//if(!$location['country']=urldecode($_COOKIE['ad_city'])){}
		//echo '</br>-'. $_COOKIE['ad_city'].'-</br>';	
		if(!$city = $_COOKIE['ad_city']){ 
			include_once "../include/city.inc.php";
			include_once "../include/fun.ip.php"; 
			$ip = getip();
			//$ip = '222.128.148.227'; 
			$iplocation = new IpLocation();
			$separator = $iplocation->separate(1000);
			$location = $iplocation->getlocation($ip);//print_r($location);print_r($city_id_name);
			
			
			//setcookie('ad_city',$location['country'],$out_time,'/','xcar.com.cn');//+1是为数组id前移 去掉0从1开始
			//setcookie('ad_city',urlencode($location['country']),$out_time,'/');
			
			//print_r($location);print_r($city_id_name);

		
				foreach($city_arr as $k=>$v){
					//echo '</br>@'.$location['country'].'</br>-'.$v. $city_id_name[$v].'--'.strstr($location['country'],$city_id_name[$v]);
					
					if(!(strpos($v,'A') !== false)){
						//echo '</br>@'.$location['country'].'</br>-'.$v. $city_id_name[$v].'--';
						//if(strstr($location['country'],$city_id_name[$v])){
						if(strpos($location['country'],$city_id_name[$v]) !== false){
							//echo '</br>'.$location['country'].'</br>'. $city_id_name[$v];
							$out_time = time()+3600;
							setcookie('ad_city',$v,$out_time,'/','xcar.com.cn');
							return true;
						}
					}else{
						continue;
					}
				}
		}else{
			if (@in_array($city, $city_arr)   ) {
			return true;
		}
		
		}
		
	}else{
		return true; 
	}
}


/* -----------------xhprof------------------------  */
/**/
if (@$_GET['xhprof'] == 1) {
     
// stop profiler
    $xhprof_data = xhprof_disable();

// display raw xhprof data for the profiler run
//print_r($xhprof_data);

   // $XHPROF_ROOT = realpath(dirname(__FILE__) );
    $XHPROF_ROOT = '/export/home/ad';

    include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
    include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";

// save raw data for this profiler run using default
// implementation of iXHProfRuns.
    $xhprof_runs = new XHProfRuns_Default();

// save the run under a namespace "xhprof_foo"
    $run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo");

    	//echo "<script language='javascript'>window.open('../xhprof_html/index.php?run=" . $run_id . "&source=xhprof_foo');</script>";
		 
		    echo "" ."<a target=\" _blank\=\"\" href=\"http://ad.xcar.com.cn/xhprof_html/index.php?run=" . $run_id . "&source=xhprof_foo\">XHProf" . "</a>";

    
}

/* -----------------xhprof------------------------ */
?>
